<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\GroupRequest;
use App\Repositories\GroupRepository;
use App\Repositories\MenuRepository;
use App\Services\PHPTree;

class GroupController extends AdminController
{
    public function __construct(GroupRepository $group, MenuRepository $menu)
    {
        $this->group = $group;
        $this->menu = $menu;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $data = $this->group->all();

        return view('admin.group', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $tree = (new PHPTree($this->menu->all()))->render();

        return view('admin.group_add', compact('tree'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(GroupRequest $request)
    {
        $data = $request->all();

        if (!$request->has('menu')) { $data['menu'] = []; }

        // $data['url'] = $this->menu->getUrls($data['menu']);

        $result = $this->group->create($data);

        if ($result) {
            return redirect()->route('admin.group.index')->with('success', '用户组添加成功'); 
        }

        return back()->with('error', '用户组添加失败');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $data = $this->group->find($id);
        $tree = (new PHPTree($this->menu->all()))->render();

        $permissions = config('permissions');


        return view('admin.group_edit', compact('data', 'tree', 'permissions'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(GroupRequest $request, $id)
    {
        $data = $request->all();

        if (!$request->has('menu')) { $data['menu'] = []; }
        
        $result = $this->group->updateFind($data, $id);

        if ($result) {
            $this->group->updatePermission();
            return redirect()->route('admin.group.index')->with('success', '用户组修改成功'); 
        }

        return back()->with('error', '用户组修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $result = $this->group->delete($id);

        if ($result) {
            flash('success', '用户组删除成功');
            return response()->json(['code' => 200]);
        }

        flash('error', '用户组删除失败');
        return response()->json(['code' => 500]);
    }
}
